# author: zhanghao
# time: 2023-12-26
# info: 这是配置加载类

import os
import json
import sys
import requests

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

from domain.rule_config import RuleConfig
from config.logger import Logger


class Config:
    logger = Logger().get()

    rule = ""
    rule_file_url = ''
    current_dir = ''
    rule_config: RuleConfig
    scheduler = BackgroundScheduler()

    def __init__(self):
        self.rule_config = RuleConfig('', '', [])
        self.current_dir = os.getcwd()
        self.logger.info(self.current_dir)

    def initConfig(self):
        self.loadConfig()

        # 启动配置文件更新定时任务
        self.logger.info('启动定时任务')
        trigger = IntervalTrigger(minutes=1)
        self.scheduler.add_job(self.downloadConfigFile, trigger)
        self.logger.info(self.rule_config)
        self.scheduler.start()
        self.logger.info('启动任务成功')

    def downloadConfigFile(self):
        self.logger.info('download OS downloadConfigFile')
        try:
            config_path = self.current_dir + '/conf/config.json'
            with open(config_path, 'r', encoding='utf-8') as f:
                config_file_json = json.load(f)
            self.logger.info(config_file_json)
            if config_file_json:
                self.rule_file_url = config_file_json['ruleFileUrl']

                # download rule file
                download_file = requests.get(self.rule_file_url)

                # judge the config file version
                if download_file:
                    download_file_json = json.loads(download_file.content)
                    version = download_file_json['version']

                    # compare version and write new rule json file
                    if self.rule_config.versionCompare(version) is True:
                        rule_path = self.current_dir + '/conf/rule.json'
                        with open(rule_path, 'w', encoding='utf-8') as file:
                            file.write(download_file.text)
                            file.close()

                        # reload new config file
                        self.loadConfig()
                    self.logger.info('download file success')

        except OSError as err:
            self.logger.exception('download OS error:', err)

        except Exception as e:
            self.logger.exception('download error:', e)

    def loadConfig(self):
        try:
            self.logger.info('加载配置.........')
            rule_path = self.current_dir + '/conf/rule.json'
            with open(rule_path, 'r', encoding='utf-8') as f:
                rule = json.load(f)
            self.logger.info(rule)
            self.rule_config = RuleConfig(rule['version'], rule['name'], rule['rules'])

        except OSError as err:
            self.logger.exception('loadConfig init OS error:', err)

        except Exception as e:
            self.logger.exception('loadConfig error:', e)

    def getVersion(self):
        return self.rule_config.version
